use std::{collections::HashSet, vec};

use chat_core::User;
use crate::{AppError,AppState, CreateMessage, ListMessages, UserMessage};
use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    response::IntoResponse,
    Extension, Json,
};



pub(crate) async fn send_message_handler(
    Extension(user): Extension<User>,
    State(state): State<AppState>,
    Path(id): Path<u64>,
    Json(input): Json<CreateMessage>,
) -> Result<impl IntoResponse,AppError>{
    let message = state.create_message(input,id,user.id as _).await?;
    Ok((StatusCode::CREATED,Json(message)))
}

pub(crate) async fn list_message_handler(
    State(state): State<AppState>,
    Path(id): Path<u64>,
    Query(params): Query<ListMessages>,
) -> Result<impl IntoResponse,AppError>{
    let messages = state.list_messages(params,id).await?;
    let sender_ids = messages.iter()
    .map(|m|
    m.sender_id)
    .collect::<HashSet<_>>()
    .into_iter()
    .collect::<Vec<i64>>();
    let users = state.fetch_users_by_ids(&sender_ids).await?;
    let mut user_message = vec![];
    for m in messages {
        if let Some(u) = users.iter().find(|u|u.id == m.sender_id) {
            let um = UserMessage{
                id: m.id as _,
                chat_id: m.chat_id as _,
                fullname: u.fullname.clone(),
                sender_id: m.sender_id as _,
                content: m.content.clone(),
                files: m.files.clone(),
                created_at: m.created_at,
            };
            user_message.push(um);
        }
    }
    Ok((StatusCode::OK,Json(user_message)))
}